package top.houry.im.client.handler.impl;

import io.netty.channel.ChannelHandlerContext;
import javafx.application.Platform;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.houry.im.client.controller.ImClientLoginUiController;
import top.houry.im.client.controller.ImClientMainUiController;
import top.houry.im.client.event.ImClientUiLoginEvent;
import top.houry.im.client.handler.ImClientMsgTypeHandler;
import top.houry.im.client.proto.ImMessage;
import top.houry.im.ui.controller.ImUiMainController;

import java.util.Date;

public class ImClientLoginHandlerImpl implements ImClientMsgTypeHandler {
    private static final Logger log = LoggerFactory.getLogger(ImClientLoginHandlerImpl.class);


    @Override
    public void processImMsg(ImMessage.Client client, ChannelHandlerContext ctx) {
        try {
            ImUiMainController mainController = ImClientMainUiController.getInstance();
            if (200 == client.getCode()) {
                Platform.runLater(() -> {
                    ImClientLoginUiController.getInstance().close();
                    mainController.show();

                    // TODO 展示历史对话框
//                    mainController.addTalkBox(-1, 0, "1001", "1001", "04_50", "ssdfsdfsdfsdfsfafdasdgagasgagasgasgasdg", null, false);
//                    mainController.addTalkBox(-1, 0, "1002", "1002", "04_50", null, null, false);
                    // 初始化好友列表

                });

                ImMessage.LoginRespMessage loginResp = ImMessage.LoginRespMessage.parseFrom(client.getBytesData());
                String userId = loginResp.getUserId();

                ImMessage.UserFriendsReq.Builder friends = ImMessage.UserFriendsReq.newBuilder();
                friends.setUserId(userId);

                ImMessage.Client.Builder friendReq = ImMessage.Client.newBuilder();
                friendReq.setMsgType("client.friends.req");
                friendReq.setBytesData(friends.build().toByteString());
                ctx.writeAndFlush(friendReq);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
